import { Injectable } from '@nestjs/common';
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { DeliveryAddressEntity } from "./delivery-address.entity";
import { ResultVo } from "../../vo/common/result.vo";

@Injectable()
export class DeliveryAddressService {
    constructor(
        @InjectRepository(DeliveryAddressEntity)
        private readonly deliveryAddressRepository: Repository<DeliveryAddressEntity>,
    ) { }

    async queryAll(userId: number) {
        let data = await this.deliveryAddressRepository.find({ order: {isDefault: "DESC"},where:{userId}})
        return ResultVo.successWithData(data)
    }

    async queryOne(id: number| string) {
        let data = await this.deliveryAddressRepository.findOne(id)
        return ResultVo.successWithData(data)
    }

    async add(data: DeliveryAddressEntity) {
        let date = new Date()
        data.createdTime = date
        data.updatedTime = date
        let res = await this.deliveryAddressRepository.save<DeliveryAddressEntity>(data)
        return ResultVo.successWithData(res)
    }

    async edit(data: DeliveryAddressEntity) {
        data.updatedTime = new Date()
        if(data.isDefault == 1){
            await this.deliveryAddressRepository.update({ userId: data.userId }, {isDefault: 0})
        }
        let res = await this.deliveryAddressRepository.update({ id: data.id }, data)
        return ResultVo.successWithData(res)
    }

    async delete(id: number | string) {
        let res = await this.deliveryAddressRepository.delete(id)
        return ResultVo.successWithData(res)
    }
}
